package com.example.cameraxdemo

import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.example.cameraxdemo.databinding.ActivityMainBinding
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.Executor

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    var executor: Executor? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        window.setFlags(
            android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN,
            android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        initCamera()
    }

    //启动相机
    private fun initCamera(){

        executor = ContextCompat.getMainExecutor(this);

        var cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(Runnable {
            // 用于将相机的生命周期绑定到生命周期所有者
            var cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

            // Preview
            var preview = Preview.Builder()
                    .build()
                    .also {
                        it.setSurfaceProvider(
                                binding.previewView.createSurfaceProvider())
                    }

            // 设置前置摄像头
            var cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA

            try {
                // Unbind use cases before rebinding
                cameraProvider.unbindAll()

                // Bind use cases to camera
                cameraProvider.bindToLifecycle(
                        this, cameraSelector, preview)
            } catch(exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, executor)
    }


}